/**
 * Desenvolvido pela Fábrica de Software do CESUPA.
 * Todos os direitos reservados.
 */
package br.cesupa.fabsoft.nomedoprojeto.system.application.facades;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;

/**
 * Manages translations for the messages used on validation.
 *
 * @author Breno Leite 
 */
public class FacesMessageTranslationContext {

    private FacesMessageFacade facesMessageFacade;

    public FacesMessageTranslationContext(final FacesMessageFacade facesMessageFacade) {
        this.facesMessageFacade = facesMessageFacade;
    }

    /**
     * Uses the given message as the key to a translated resource stored in the
     * <code>faces-validation.properties</code> resource bundle.
     */
    public void translated() {
        FacesContext.getCurrentInstance().addMessage(
                facesMessageFacade.getComponentId(),
                new FacesMessage(facesMessageFacade.getSeverity(),
                translateMessage(facesMessageFacade.getMessage()),
                translateMessageDetails(facesMessageFacade.getMessage())));
    }

    /**
     * Uses no resource bundle. The given message is the text that will be
     * showed in the view.
     */
    public void withoutTranslation() {
        FacesContext.getCurrentInstance().addMessage(
                facesMessageFacade.getComponentId(),
                new FacesMessage(facesMessageFacade.getSeverity(),
                facesMessageFacade.getMessage(), facesMessageFacade.getMessage()));
    }

    /**
     * @see TranslationFacade#translateFacesMessage(java.lang.String)
     */
    private String translateMessage(final String message) {
        return ApplicationFacade.getTranslationFacade().translateFacesMessage(message);
    }

    /**
     * @see TranslationFacade#translateFacesMessage(java.lang.String)
     */
    private String translateMessageDetails(final String message) {
        String translatedMessage = ApplicationFacade.getTranslationFacade().
                translateFacesMessage(message + ".DETAILS");

        if (translatedMessage.equals(message + ".DETAILS")) {
            return null;
        } else {
            return translatedMessage;
        }
    }
}
